package com.itany.book.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import com.itany.book.exception.UserPhoneExistsException;
import com.itany.book.user.service.IUserService;
import com.itany.book.pojo.User;
import com.itany.book.utils.MSNSender;
import com.itany.book.vo.ActionResult;
import com.itany.book.vo.ResponseResult;
import jdk.nashorn.internal.ir.ReturnNode;
import org.jasig.cas.client.util.AbstractCasFilter;
import org.jasig.cas.client.validation.Assertion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.security.Principal;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * Created by tyh on 2018/9/22.
 */
@Controller
@RequestMapping("/userserver")
public class UserController {

    @Reference
    private IUserService userService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @RequestMapping("/addUser")
    @ResponseBody
    public ActionResult addUser(User user){
        ActionResult ac= new ActionResult();
        userService.addUser(user);
        ac.setStatus(0);
        return ac;
    }

    @RequestMapping("/findUsers")
    public ModelAndView findUsers(@RequestParam(defaultValue = "1")Integer pageNo,
                                  @RequestParam(defaultValue = "10")Integer pageSize){
        PageInfo<User> pageInfo =  userService.findUsers(pageNo,pageSize);
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("pageInfo",pageInfo);
        return new ModelAndView("userlist",map);
    }

    //self
    // @RequestMapping("/login")
    public String login(User user, HttpServletResponse response){
        User u =   userService.login(user);
        u.setPassword(null);
        //生成token
        String token = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set("USER_TOKEN::"+token, JSON.toJSONString(u),1800, TimeUnit.SECONDS);
        //放入cookie
        Cookie cookie =new Cookie("TT_TOKEN",token);
        // 设置前端页面，对于所有的/ 的请求， 都会携带cookie,因为我们的项目没有应用名。
        cookie.setPath("/");
        response.addCookie(cookie);
        return "redirect:http://localhost:9003/user/userserver/findUsers";
    }

    // get验证码 返回界面
    // 暂存在手机号里面
    //

    /**
     * 生成短信验证码，
     * 并通过聚合平台发送给用户
     * 并将验证码保存在session中
     * @param phone
     * @param session
     */
    @RequestMapping("/getMSNVerCode")
    @ResponseBody
    public ResponseResult getMSNVerCode(String phone, HttpSession session){
        String codes = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        Random random = new Random();
        String code ="";
        for (int i=0;i<6;i++){
            code += codes.charAt(random.nextInt(codes.length()));
        }
        random.nextInt();
        // MSNSender.sendMsg(phone, code);
        System.out.println("-------------");
        System.out.println(code);
        System.out.println(phone);
        session.setAttribute("MSNVerCode",code);
        // 成功了
        // MSNSender.sendMsg(phone,code);
        System.out.println(session.getAttribute("MSNVerCode"));
        return ResponseResult.success();
    }

    @RequestMapping("/register")
    @ResponseBody
    public ResponseResult register(User user, HttpSession session, String MSNcode){
        System.out.println("进入注册页面");
        // 调用第三方放入到session中的值。
        String mycode = (String) session.getAttribute("MSNVerCode");
        if (! mycode.equals(MSNcode)){
            return ResponseResult.fail("短信验证码不正确！");
        }
        // 先查找，未找到，在注册！
        user.setFlag(1);
        try {
            userService.register(user);
        } catch (UserPhoneExistsException e) {
            e.printStackTrace();
            return ResponseResult.fail(e.getMessage());
        }
        return ResponseResult.success();
    }

    //
    @RequestMapping("/casIndex")
    public String casIndex(HttpServletRequest request){
        // 还有casClient的参数
        Assertion assertion = (Assertion) request.getSession().getAttribute(AbstractCasFilter.CONST_CAS_ASSERTION);
        // 里面有用户信息
        Principal principal = assertion.getPrincipal();
        System.out.println("=========="+principal.getName());
        return "login";
    }

    @RequestMapping("/casLogOut")
    public String casLogOut(HttpSession session){
        session.invalidate();
        return "redirect:http://localhost:8443/cas/logout";
    }

}
